﻿using IService;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Service;

public class LoginController : Controller
{
    private readonly string _connectionString;

    public LoginController(IConfiguration configuration)
    {
        _connectionString = configuration.GetConnectionString("DefaultConnection");
    }

    /// <summary>
    /// 生成验证码图片的接口
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    public IActionResult CaptchaImage()
    {
        string captchaCode = CaptchaHelper.GenerateCaptchaCode(4); // 生成随机验证码
        HttpContext.Session.SetString("CaptchaCode", captchaCode); // 存入 Session
        byte[] imageData = CaptchaHelper.GenerateCaptchaImage(captchaCode); // 生成图片
        return File(imageData, "image/png"); // 返回图片
    }

    // 显示登录页
    [HttpGet]
    public IActionResult Login()
    {
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Login(string username, string password, string captcha)
    {
        // 1. 验证验证码
        string sessionCaptcha = HttpContext.Session.GetString("CaptchaCode");
        if (string.IsNullOrEmpty(sessionCaptcha) ||
            !string.Equals(captcha, sessionCaptcha, StringComparison.OrdinalIgnoreCase))
        {
            ViewBag.ErrorMessage = "验证码不正确，请重新输入";
            HttpContext.Session.Remove("CaptchaCode");
            return View();
        }
        HttpContext.Session.Remove("CaptchaCode"); // 清除验证码（一次性使用）

        // 2. 先验证账号密码（业务逻辑优先）
        ILoginService loginService = new LoginService();
        if (!loginService.Login(username, password, _connectionString))
        {
            ViewBag.ErrorMessage = "账号或密码错误，请重新输入";
            return View(); // 验证失败，直接返回登录页，不存Session
        }

        // 3. 只有账号密码验证成功后，才存入Session（关键修正）
        HttpContext.Session.SetString("LoginUserName", username);
        Console.WriteLine($"【登录成功】将用户名 {username} 存入Session");

        // 4. 登录成功，重定向到首页
        return RedirectToAction("Index", "Home");
    }


    /// <summary>
    /// 处理注销逻辑
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    public IActionResult Logout()
    {
        // 彻底清除所有Session
        HttpContext.Session.Clear();

        // 禁止Logout页面自身的缓存
        Response.Headers["Cache-Control"] = "no-cache, no-store, must-revalidate";
        Response.Headers["Pragma"] = "no-cache";
        Response.Headers["Expires"] = "0";

        return RedirectToAction("Login", "Login");
    }
}   